﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Interfaces;
using Cofe.Core.Property;
using Cofe.Core.Service;

namespace Cofe.Core.EntryLinks
{
    public class EntryLinkSecondaryPP : PropertyProviderBase, IEntryLinkSecondaryPP
    {
        #region Constructor

        public EntryLinkSecondaryPP(IContainerBehavior linkContainerBehavior)
        {
            ContainerBehavior = linkContainerBehavior;

            registerAction<IPropertyHost>(CofeEntryLinkProperties.AddLink, (pd) => addLink(pd));
            registerAction(CofeEntryLinkProperties.DeleteChildLink, (pd) => removeLink(pd));
            registerAction<IEnumerable<IPropertyHost>>(CofeEntryLinkProperties.GetLinks, (pd) => getLinks(pd));
        }

        #endregion

        #region Methods

        IPropertyHost addLink(ParameterDic pd)
        {
            string label = pd.ContainsKey("Label") ? pd["Label"] as string : null;
            string parseName = pd.ContainsKey("ParseName") ? pd["ParseName"] as string : null;
            ParsableType pt = pd.ContainsKey("ParseType") ? (ParsableType)pd["ParseType"] : ParsableType.ParsePathLookup;

            if (String.IsNullOrEmpty(label)) throw new ArgumentException("Label");
            if (String.IsNullOrEmpty(parseName)) throw new ArgumentException("ParseName");

            pd.IsHandled = true;
            return ContainerBehavior.Add(-1, label, parseName, pt);
        }

        void removeLink(ParameterDic pd)
        {
            string label = pd.ContainsKey("Label") ? pd["Label"] as string : null;
            if (String.IsNullOrEmpty(label)) throw new ArgumentException("Label");
            pd.IsHandled = true;
            ContainerBehavior.Remove(label);
        }

        IEnumerable<IPropertyHost> getLinks(ParameterDic pd)
        {
            foreach (var l in ContainerBehavior.GetLabels())
                yield return ContainerBehavior.GetItem(l);
        }

        #endregion

        #region Data

        #endregion

        #region Public Properties

        public IContainerBehavior ContainerBehavior { get; private set; }

        #endregion

    }

    
}
